package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住表Service业务层处理
 * 
 * @author xw
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住表
     * 
     * @param id 入住表主键
     * @return 入住表
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住表列表
     * 
     * @param checkIn 入住表
     * @return 入住表
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住表
     * 
     * @param checkIn 入住表
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住表
     * 
     * @param ids 需要删除的入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住表信息
     * 
     * @param id 入住表主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }


    /**
     * 申请入住
     * @param checkInApplyDto
     */
    /*@Override
    @Transactional(rollbackFor = Exception.class)
    public void applyForCheckIn(CheckInApplyDto checkInApplyDto) {
        //校验老人是否已经入住,如果已经入住,则提示已经入住结束流程,根据身份证号号查身份证号都是唯一的
        LambdaQueryWrapper<Elder> wrapper=new LambdaQueryWrapper<>();
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        wrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo())
                .in(Elder::getStatus,1,4);
        Elder elder=elderMapper.selectOne(wrapper);//获取到该老人信息
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new RuntimeException("该老人已经入住,请勿重复入住");
        }
        //如果没有入住,更新床位状态为已入住
        Bed bed = new Bed();
        bed.setId(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bed.setBedNumber(bedMapper.selectBedById(bed.getId()).toString());
        bedMapper.updateStatus(bed) ;
        //新增或更新老人基本信息//新增或更新老人家属信息
        Elder ed = new Elder();
        ed.setBedId(checkInApplyDto.getCheckInConfigDto().getBedId());
        //ed.set
       // ed.setBedNumber(bed.getBedNumber());
        BeanUtils.copyProperties(checkInElderDto,ed);
        ed.setRemark(checkInApplyDto.getElderFamilyDtoList().toString());
        if (ObjectUtil.isEmpty(ed.getId())){
            elderMapper.insert(ed);
        }else{
            elderMapper.updateById(ed);
        }
//        CheckIn checkIn = new CheckIn();
//        checkIn.setElderId(ed.getId());
//        checkIn.setBedNumber(ed.getBedNumber());
//        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
//        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
//        checkIn.setRemark(ed.getRemark());
//        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(),checkIn);
//        checkInMapper.insertCheckIn(checkIn);
        //新增或更新老人签约信息
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        Contract contract = new Contract();
        //生成唯一合同编号
        contract.setContractNumber(DateUtils.getDate()+"-"+ed.getId());
        BeanUtils.copyProperties(checkInContractDto,contract);
        contract.setElderId(Math.toIntExact(ed.getId()));
        contractMapper.insertContract(contract);
        //新增老人入住配置信息
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfigMapper.insertCheckInConfig(checkInConfig);

    }*/


    /**
     * 申请入住
     *
     * @param checkInApplyDto 申请入住表单数据
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void applyForCheckIn(CheckInApplyDto checkInApplyDto) {
        // 1.校验老人是否已入住，如果已入住，直接结束流程
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .in(Elder::getStatus, 1, 4);
        Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);

        if (ObjectUtil.isNotEmpty(elder)) {
            throw new BaseException("该老人已入住，请勿重复申请入住");
        }

        // 2.如果没有入住，更新床位状态为已入住
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectById(bedId);  // 根据床位id查询床位对象
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        // 3.新增或更新老人基本信息（返回值类型待定）
        elder = insertOrUpdateElder(checkInElderDto, bed);

        // 4.新增签约办理
        insertContract(elder, checkInApplyDto.getCheckInContractDto(), checkInApplyDto.getCheckInConfigDto());

        // 5.新增入住信息（同时保存家属信息到remark字段）
        CheckIn checkIn = insertCheckInInfo(elder, bed, checkInApplyDto.getCheckInConfigDto(), checkInApplyDto.getElderFamilyDtoList());

        // 6.新增入住配置
        insertCheckInConfig(checkIn, checkInApplyDto.getCheckInConfigDto());
    }

    /**
     * 保存入住配置
     * @param checkIn   入住信息
     * @param checkInConfigDto  入住配置信息
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        checkInConfig.setCheckInId(checkIn.getId());
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);

        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder 老人信息
     * @param bed   老人入住床位
     * @param checkInConfigDto  入住配置
     * @param elderFamilyDtoList    老人家属列表
     */
    private CheckIn insertCheckInInfo(Elder elder, Bed bed, CheckInConfigDto checkInConfigDto, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
//        checkIn.setStatus(0);
        // 老人家属信息
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));

        checkInMapper.insert(checkIn);
        return checkIn;
    }



    /**
     * 新增合同，签约办理
     * @param elder 老人信息
     * @param checkInContractDto    合同信息
     * @param checkInConfigDto      入住配置信息
     */
    private void insertContract(Elder elder, CheckInContractDto checkInContractDto, CheckInConfigDto checkInConfigDto) {
        Contract contract = new Contract();
        contract.setElderId(Integer.valueOf(String.valueOf(elder.getId())));
        BeanUtils.copyProperties(checkInContractDto, contract);
        // 生成一个合同编号
        String contractNumber = DateUtils.getDate() + "-" + elder.getId();
        contract.setContractNumber(contractNumber);

        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        // 假设一开始合同状态都为未生效
//        contract.setStatus(0);

        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人信息
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        // 判断要新增还是更新老人
        String idCardNo = checkInElderDto.getIdCardNo();
        LambdaQueryWrapper<Elder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Elder::getIdCardNo, idCardNo);
        Elder elder = elderMapper.selectOne(wrapper);

        if (ObjectUtil.isNotEmpty(elder)) {
            // 更新老人信息
            // 更新状态为1
            elder.setStatus(1);
            // 更新前端传过来的其他基本信息
            BeanUtils.copyProperties(checkInElderDto, elder);
            // 更新床位信息
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.updateById(elder);
        } else {
            // 新增老人信息
            elder = new Elder();
            elder.setStatus(1);
            BeanUtils.copyProperties(checkInElderDto, elder);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.insert(elder);
        }
        return elder;
    }
    //传入的是入住表的id
    @Override
    public CheckInDetailVo getCheckInDetail(Long id) {

        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        Elder elder = elderMapper.selectElderById(checkIn.getElderId());

        LambdaQueryWrapper<CheckInConfig> wrappper = new LambdaQueryWrapper<>();
        wrappper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(wrappper);

        LambdaQueryWrapper<Contract> CWrapper = new LambdaQueryWrapper<>();
        CWrapper.eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(CWrapper);

        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInElderVo checkInElderVo = new CheckInElderVo();


        BeanUtils.copyProperties(elder, checkInElderVo);
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);


        List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));

        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}


